import axios, {AxiosResponse} from "axios";
import {ElMessage} from "element-plus";
import useUserStore from "@/store/modules/user.ts";

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout:5000,
})

request.interceptors.request.use(config => {
  const userStore = useUserStore();
  const token = userStore.userInfo.token;
  if(token){
    config.headers.token = token;
  }
  return config
})

request.interceptors.response.use(response => {
  if(response.data instanceof Blob){
    return response.data
  }
  const {code} = response.data;
  if(code === 200){
    return response.data
  }
  errorCode[code]?.(response)
  return Promise.reject(response)
},error => {
  console.log(error)
  const {status} =error;
  httpErrorCode[status]?.(error)
  return Promise.reject(error)
})
/**
 * 业务错误码处理
 */
const errorCode: Record<number, (response:AxiosResponse<any,any>) => void> = {
  401: (response:AxiosResponse<any,any>) => {
    ElMessage.error(response.data.message)
  },
  403: (response:AxiosResponse<any,any>) => {
    ElMessage.error(response.data.message)
  },
  404:  (response:AxiosResponse<any,any>) => {
    ElMessage.error(response.data.message)
  },
  500:  (response:AxiosResponse<any,any>) => {
    ElMessage.error(response.data.message)
  },
  501: (response:AxiosResponse<any,any>) => {
    ElMessage.error(response.data.message)
  }
}
// http状态码处理
const httpErrorCode: Record<number, (error:any) => void> = {
  401 : () => {
    ElMessage.error("未授权，请重新登录")
  },
  403 : () => {
    ElMessage.error("权限不足，请重新登录或联系管理员")
  },
  404 : (error:any) => {
    ElMessage.error("接口不存在，请求路径: " + error.request.responseURL)
  },
  500 : () => {
    ElMessage.error("服务器出错，请联系管理员")
  },
  400 : (error:any) => {
    ElMessage.error("请求无法被服务器处理，" + error.message)
  }
}
export default request
